package com.linln.admin.system.web;

import com.github.pagehelper.Page;
import com.google.gson.Gson;
import com.linln.admin.system.config.QiNiuConfig;
import com.linln.common.exception.ResultException;
import com.linln.common.utils.HttpServletUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.fileUpload.enums.UploadResultEnum;
import com.linln.modules.system.dao.CustomMapper;
import com.linln.modules.system.dto.ProdSubDto;
import com.linln.modules.system.dto.ProductDto;
import com.linln.modules.system.entity.BeautyCompany;
import com.linln.modules.system.entity.BeautyProduct;
import com.linln.modules.system.entity.ProdSub;
import com.linln.modules.system.entity.ProductPics;
import com.linln.modules.system.entity.WxUser;
import com.linln.modules.system.service.CompanyService;
import com.linln.modules.system.service.ProductServices;
import com.linln.modules.system.service.WxUserServices;
import com.linln.modules.system.vo.admins.AdminProductVo;
import com.linln.modules.system.vo.admins.ProductDetailVo;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Controller
@RequestMapping(value = "/mains/product")
public class ProductController extends BaseController {

    protected final Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductServices productServices;

    @Autowired
    private CompanyService companyService;
    @Autowired
    private CustomMapper customMapper;



    @RequestMapping(value = "/index")
    @RequiresPermissions("mains:product:index")
    public ModelAndView getIndex(Integer pageNum)  {
        Integer pageIndex = HttpServletUtil.getParameterInt("size", 1);
        pageNum = pageNum == null ? super.pageNum : pageNum;
        ModelAndView view = new ModelAndView();
        view.setViewName("/mains/product/index");
        Page<AdminProductVo> company = productServices.getIndexPager(pageNum, pageIndex*10, null);
        view.addObject("list", company.getResult());
        view.addObject("page", company);
        return view;
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    public String toAdd(Model model) {
        List<BeautyCompany> list = companyService.getCompanyList();
        model.addAttribute("company",list);
        return "/mains/product/add";
    }

    @RequestMapping(value = "/orders/{id}")
    public String editOrder(Model model,@PathVariable("id") String id){
        BeautyProduct product = productServices.getBeautyProductById(id);
        model.addAttribute("prodId",id);
        model.addAttribute("sorts",product.getSorts());
        return "/mains/product/editOrder";
    }


    @ResponseBody
    @RequestMapping(value = "saveOrder")
    public ResultVo saveProductOrder(String id,Integer sorts){
        ResultVo vo = ResultVoUtil.error("操作失败");
        try {
            int end = productServices.saveProductOrder(id,sorts);
            if(end>0){
                vo.setCode(200);
                vo.setMsg("操作成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }

    @ResponseBody
    @RequestMapping(value = "save",method = RequestMethod.POST)
    public ResultVo saveProduct(ProductDto dto, ProdSubDto sdto){
        ResultVo vo = ResultVoUtil.error("操作失败");
        try {
            int end = productServices.saveProduct(dto,sdto);
            if(end>0){
                vo.setCode(200);
                vo.setMsg("操作成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }

    @ResponseBody
    @RequestMapping(value = "update",method = RequestMethod.POST)
    public ResultVo updateProduct(ProductDto dto,ProdSubDto sdto){
        ResultVo vo = ResultVoUtil.error("操作失败");
        try {
            int end = productServices.updateProduct(dto,sdto);
            if(end>0){
                vo.setCode(200);
                vo.setMsg("操作成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }


    /**
     * 详细信息
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "detail/{id}")
    public String getDetailById(@PathVariable("id") String id,Model model){
        try {
            ProductDetailVo vo = productServices.getProductDetailVoById(id);
            if(vo.getKinds()==2){
                List<ProdSub> list = productServices.getProdSubs(id);
                model.addAttribute("listProd",list);
            }
            List<String> urls = productServices.picUrls(id);
            if(urls!=null){
                model.addAttribute("urls",urls);
            }else {
                model.addAttribute("urls", Arrays.asList(vo.getImages()));
            }
            model.addAttribute("product",vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/mains/product/detail";
    }


    @RequestMapping(value = "edit/{id}")
    public String toEdit(@PathVariable("id") String id,Model model){
        List<BeautyCompany> list = companyService.getCompanyList();
        BeautyProduct product = productServices.getBeautyProductById(id);
        if(product.getKinds()==2){
            List<ProdSub> subList = productServices.getProdSubs(id);
            model.addAttribute("listProd",subList);
        }
        List<ProductPics> urls = productServices.getPicUrls(id);
        if(urls!=null){
            model.addAttribute("urls",urls);
        }
        model.addAttribute("product",product);
        model.addAttribute("company",list);
        return "/mains/product/edit";
    }

    @ResponseBody
    @RequestMapping(value = "del/{id}")
    public ResultVo  toDelete(@PathVariable("id") String id){
        ResultVo vo = ResultVoUtil.error("操作失败");
        try {
            BeautyProduct product = productServices.getBeautyProductById(id);
            if(product.getKinds()==2){
                customMapper.updateOldSub(id);
            }
            int i = productServices.deleteProduct(id, 1);

            if(i>0){
                vo.setMsg("删除成功");
                vo.setCode(200);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }


    @ResponseBody
    @RequestMapping(value = "status/{state}/{id}")
    public ResultVo toBanPick(@PathVariable("id") String id,@PathVariable("state") Integer state){
        ResultVo vo = ResultVoUtil.error("操作失败");
        try {
            int i = productServices.lockAndRelease(id, state);
            if(i>0){
                vo.setMsg("操作成功");
                vo.setCode(200);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;
    }


    @ResponseBody
    @PostMapping("/upload")
    public ResultVo uploadImage(@RequestParam("image") MultipartFile multipartFile) {
        if (multipartFile.getSize() == 0){
            throw new ResultException(UploadResultEnum.NO_FILE_NULL);
        }
        try {
            logger.info("上传文件开始,fileName:{}", multipartFile.getOriginalFilename());
            String fileType = StringUtils.substringAfterLast(multipartFile.getOriginalFilename(), ".");
            String fullPath = "quickLove/" + generateFileName(fileType);
            asyncUpload(fullPath, multipartFile.getInputStream());
            String sendPath = qiNiuConfig.getDomainHost() + fullPath;
            return ResultVoUtil.success("上传成功",sendPath);
        }catch (Exception es){
            return ResultVoUtil.error("上传失败");
        }
    }

    @Autowired
    private QiNiuConfig qiNiuConfig;
    /**
     * 异步上传数据
     *
     * @param fileName
     * @param input
     */
    private void asyncUpload(String fileName, InputStream input) {
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = qiNiuConfig.getAppKey();
        String secretKey = qiNiuConfig.getAppSecret();
        String bucket = qiNiuConfig.getBucketName1();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(input, fileName, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
            }
        }
    }

    @Autowired
    private AtomicInteger atomicInteger;
    public String generateFileName(String fileType) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        StringBuilder sb = new StringBuilder();
        sb.append(year);
        sb.append("/");
        sb.append(calendar.get(Calendar.MONTH) + 1);
        sb.append("/");
        sb.append(calendar.get(Calendar.DAY_OF_MONTH));
        sb.append("-");
        sb.append(calendar.get(Calendar.HOUR_OF_DAY));// 1位
        sb.append(calendar.get(Calendar.MINUTE));// 1位
        sb.append(calendar.get(Calendar.SECOND));// 1位
        sb.append("-");
        sb.append(atomicInteger.getAndIncrement());
        sb.append(RandomStringUtils.randomAlphanumeric(6));
        sb.append(".");
        sb.append(fileType);
        return sb.toString();
    }
}
